﻿using Sprout.Core;
using Sprout.Core.Extensions;
using Sprout.Core.Security;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;
using Sprout.Schedule.Web.Options;
using Sprout.Schedule.Web.Models;

namespace Sprout.Schedule.Web.Utils
{
    public class LoginHelper
    {
        private static string TokenName = "UserToken";
        public static void SetCurrent(string token)
        {
            SessionHelper.Write(TokenName, token);
        }
        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        public static string GetToken()
        {
            string token = SessionHelper.Get(TokenName);
            return token == null ? string.Empty : token;
        }

        /// <summary>
        /// Api接口需要传入apiToken
        /// </summary>
        public static void RemoveCurrent()
        {
            SessionHelper.Remove(TokenName);
        }

        /// <summary>
        /// Api接口需要传入apiToken
        /// </summary>
        /// <param name="apiToken"></param>
        /// <returns></returns>
        public static LoginUserDto GetLoginUser(HttpContext context)
        {
            string token = string.Empty;
            //token = CookieHelper.Get(TokenName);
            token = SessionHelper.Get(TokenName);
            token = string.IsNullOrEmpty(token) ? context.Request.Headers["Token"].ToString() : token;
            if (string.IsNullOrEmpty(token))
            {
                return null;
            }
            try
            {
                var appSettingOption = ServiceLocator.GetOption<AppSettingOption>();
                var json = AESHelper.Decrypt(token, appSettingOption.LoginSecurityKey);
                var loginUser = json.FromJsonString<LoginUserDto>();
                return loginUser;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
